#include <muduo/net/TcpServer.h>
#include <muduo/base/Logging.h>
#include <boost/bind.hpp>
#include <muduo/net/EventLoop.h>
#include "sqlpc.hpp"
#include "Zibprotol.hpp"
#include <unordered_map>


class EchoServer
{
public:
    EchoServer(muduo::net::EventLoop *loop,
               const muduo::net::InetAddress &listenAddr);

    void start();

private:
    void onConnection(const muduo::net::TcpConnectionPtr &conn);

    void onMessage(const muduo::net::TcpConnectionPtr &conn,
                   muduo::net::Buffer *buf,
                   muduo::Timestamp time);

    muduo::net::TcpServer server_;

    std::unordered_map<muduo::net::TcpConnectionPtr, int> appconns_;
    std::unordered_map<muduo::net::TcpConnectionPtr, int> liunxconns_;
    std::unordered_map<muduo::net::TcpConnectionPtr, int> cldconns_;
    Data_get dd;

private:

};



EchoServer::EchoServer(muduo::net::EventLoop *loop,
                       const muduo::net::InetAddress &listenAddr)
    : server_(loop, listenAddr, "EchoServer")
{
    dd.InitSql();
    server_.setConnectionCallback(
        boost::bind(&EchoServer::onConnection, this, _1));
    server_.setMessageCallback(
        boost::bind(&EchoServer::onMessage, this, _1, _2, _3));
}

void EchoServer::start()
{
    server_.start();
}

void EchoServer::onConnection(const muduo::net::TcpConnectionPtr &conn)
{
    LOG_INFO << "EchoServer - " << conn->peerAddress().toIpPort() << " -> "
             << conn->localAddress().toIpPort() << " is "
             << (conn->connected() ? "UP" : "DOWN");
}

void EchoServer::onMessage(const muduo::net::TcpConnectionPtr &conn,
                           muduo::net::Buffer *buf,
                           muduo::Timestamp time)
{
    // 接收到所有的消息，然后回显
    muduo::string msg(buf->retrieveAllAsString());
    LOG_INFO << conn->name() << " echo " << msg.size() << " bytes, "
             << "data received at " << time.toString();
    LOG_INFO << msg;
    Zibprotol zz;

    if (zz.jgcfrom(msg) == 0)
    {
        LOG_INFO << "msg error";
        return;
    }
    else if (zz.jgcfrom(msg) == 1)
    {
        if (liunxconns_[conn] == 0)
        {
            liunxconns_[conn]++;
        }
        auto sensor_data = zz.parseData(msg);
        for (const auto &data : sensor_data)
        {
            std::cout << "Temperature: " << data.temp << ", Humidity: " << data.humi << std::endl;
            dd.Savedata(data.humi, data.temp);
        }
    }
    else if (zz.jgcfrom(msg) == 2)
    {
        if (appconns_[conn] == 0)
        {
            appconns_[conn]++;
        }
        else
        {

        }
    }
    else if (zz.jgcfrom(msg) == 3)
    {
        if (cldconns_[conn] == 0)
        {
            cldconns_[conn]++;
        }
    }

    // conn->send(msg);
}

int main()
{
    LOG_INFO << "pid = " << getpid();
    muduo::net::EventLoop loop;
    muduo::net::InetAddress listenAddr(8888);
    EchoServer server(&loop, listenAddr);
    server.start();
    loop.loop();
}
